//
//  AnimateLinkManager.m
//  myfish
//
//  Created by EmberWei on 2018/6/6.
//  Copyright © 2018年 EmberWei. All rights reserved.
//

#import "AnimateLinkManager.h"

@interface AnimateLinkManager()

@property (strong, nonatomic)  CADisplayLink *displayLink;
@property (strong, nonatomic)  UIImageView *loadingImageView;
@property (assign, nonatomic)  NSInteger loadingIndex;

@property (nonatomic,assign) NSInteger count;
@property (nonatomic,strong) NSString *name;
@end

@implementation AnimateLinkManager

+(AnimateLinkManager*)initWithName:(NSString*)name count:(NSInteger)count fps:(NSInteger)fps imageView:(UIImageView*)imageView;
{
    AnimateLinkManager *link =  [AnimateLinkManager alloc];
    link.loadingIndex = 1;
    link.count  = count;
    link.name = name;
    link.loadingImageView = imageView;
    link.displayLink = [CADisplayLink displayLinkWithTarget:link selector:@selector(updateImage)];
    link.displayLink.frameInterval = 60.0 / fps;
    return link;
}

-(void)start
{
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void)stop
{
    [self.displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    self.displayLink = nil;
    self.loadingImageView.image = nil;
}

-(void)updateImage
{
    UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"%@%02td",self.name,self.loadingIndex]];
    self.loadingImageView.image = image;
    self.loadingIndex += 1;
    if(self.loadingIndex > self.count)
    {
        self.loadingIndex = 1;
    }
}


@end
